package nio.Bchannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @author 帅小伙
 * @date 2022/1/14
 * @description
 * buffer的分散和聚合
 */
public class ScatteringAndGatheringTest {

    public static void main(String[] args) throws Exception {
        // 使用  serverSocketChannel  和    socketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

        // 绑定端口  并启动
        serverSocketChannel.bind(inetSocketAddress);

        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        // 等待客户端连接
        SocketChannel socketChannel = serverSocketChannel.accept();

        // 循环读取
        // 假定加8个字节
        int messageLength = 8;
        while(true){
            int byteRead = 0;
            while(byteRead < messageLength){
                long read = socketChannel.read(byteBuffers);
                byteRead += read;
                System.out.println("byteRead = "+ byteRead);
                // 使用流打印  buffer的
                Arrays.asList(byteBuffers)
                        .stream()
                        .map(buffer -> "position = "+buffer.position()+"limit = " + buffer.limit())
                        .forEach(System.out::println);
            }

            // 将所有buffer 进行反转
            Arrays.asList(byteBuffers).forEach(buffer -> buffer.flip());
            // 将数据读出显示到客户端
            long byteWrite = 0;
            while(byteWrite < messageLength){
                long write = socketChannel.write(byteBuffers);
                byteWrite+=write;
            }

            // 所有buffer复位
            Arrays.asList(byteBuffers).forEach(buffer -> buffer.clear());
            System.out.println("byteRead:=" + byteRead + "byteWrite:=" + byteWrite);
        }
    }
}
